from rank.feature import Feature


class AuthorityFeature(Feature):
    def get_feature(self, global_resource, request_content, response_content):
        """
        获取merge_result 中的所有用户权威性
        :return:
        """
        merge_result = response_content.get_value("merge_result")
        developer_set = set()
        for api_id, api in merge_result.items():
            for developer in api["developer_ids"]:
                developer_set.add(developer)
        developer_set = list(developer_set)

        # post query获取这些developer的权威性,一次发送１０个名称，得到所有的developer auth
        body = {"query": {"terms": {"user_id": []}}}
        body["query"]["terms"]["user_id"] = developer_set
        # 找到每个api auth最高的developer，作为其auth
        es_service = global_resource.resource_manager.get_service("es_client")
        data_list = es_service.post_query("user", "user", body)
        developer_map = {user["user_id"]: user for user in data_list}

        authority_map = {}
        for api_id, api in merge_result.items():
            cur_max = 0
            for author in api["developer_ids"]:
                cur_max = max(cur_max, developer_map[author])
            authority_map[api_id] = cur_max
        response_content.store_value("authority_map", authority_map)

